package com.web.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.web.model.PageEdit;
import com.web.model.PageInfo;
import com.web.model.PageTitleImage;
import com.web.model.TypeInfo;
import com.web.util.*;
import com.web.util.aliyun.ReplaceImgURL;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * Created by root on 7/26/15.
 */
public class EditController extends Controller {

    /*新建logger对象*/
    private static final Logger LOGGER = Logger.getLogger(EditController.class);

    /**
     * 上传标题图片
     * 接口调用地址：http://ipaderess/editorJfinalProject/edit/uploadTitleImage
     */
    public void uploadTitleImage() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        Date today = new Date();

        //TODO:云服务器&本地Linxu服务器
        String saveDir = Properties.ImgSaveDir_Linux + sdf.format(new Date());

        //TODO:本地Windows服务器
//        String saveDir = Properties.ImgSaveDir_Windows + sdf.format(today);

        /*获取上传图片文件，存储到本地*/
        UploadFile titleImage = getFile("titleImage", saveDir);

        LOGGER.info("上传图片信息： " + titleImage.getSaveDirectory() + titleImage.getFileName());
        if (titleImage == null) {
            LOGGER.error("上传图片未获取到...");
        }

        /*压缩图片*/
        String inputDir = saveDir;
        String outputDir = saveDir;
        String inputFileName = titleImage.getFileName();
        /*************************************/
        String dateUnixStr = String.valueOf(new Date().getTime()); //unix时间的字符串形式：1. imageId; 2. 文件名前缀;
        String dateStr = sdf.format(today); // 日期的格式化字符串表示

        /*************************************/

        // 图片重命名
        String outputFileName = dateUnixStr + ".jpg";
        File uploadImg = new File(saveDir + inputFileName);
        uploadImg.renameTo(new File(outputDir + outputFileName));
        /**
         * inputDir: 源文件路径
         * inputFileName: 源文件名
         * outputDir: 目的文件路径
         * outputFileName: 目的文件名
         * 第一个800: 宽度
         * 第二个800: 高度
         * true: 是否等比例缩放
         * 压缩后图像的最长边在770左右
         */
        //CompressPic.compressPic.compressPic(inputDir, outputDir, inputFileName, outputFileName, 800, 800, true);

        //将标题图片上传到OSS
        String titleImgUrl = new String();
        try {
            titleImgUrl = ReplaceImgURL.replaceTitleUrl(outputDir + outputFileName);
        } catch (IOException e) {
            LOGGER.error("将标题图片上传到OSS出错", e);
        }

        // 存储压缩后的图片地址到数据库
        try {
            new PageTitleImage().set("imageId", dateUnixStr).set("imageSource", titleImgUrl).save();
        } catch (Exception exception) {
            LOGGER.error("存储压缩后的原图到数据库出错", exception);
        }

        /*删除原文件图片*/
        File image = new File(inputDir + inputFileName);
        if (image.exists()) {
            image.delete();
        }

        /*删除压缩后的存于本地的图片*/
        File image2 = new File(outputDir + outputFileName);
        if (image2.exists()) {
            image2.delete();
        }

        //TODO:本地Windows服务器
        //String imageSrc = Properties.ImgSrc_Windows + sdf.format(new Date()) + outputFileName;

        //TODO:本地linux服务器
        //String imageSrc = Properties.ImgSrc_LocalLinux + sdf.format(new Date()) + outputFileName;

        //TODO:云端服务器
//        String imageSrc = Properties.ImgSrc_CloudServer + sdf.format(new Date()) + outputFileName;


        /*向裁剪页面发送图片信息*/
//        setAttr("src", imageSrc);
        setAttr("src", titleImgUrl);
        /*图片物理地址发送到客户端*/
//        setAttr("localPicPath", saveDir + outputFileName);
        setAttr("imageId", dateUnixStr); // 发送图片imageId到客户端

        renderJsp("/newUploadAndCutImage.jsp");
        //renderJsp("/selectImage.jsp");
    }

    /**
     * 上传新的图片，根据pageId确定是哪个。。。。。
     */
    public void uploadNewTitleImage() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        Date today = new Date();

        //TODO:云服务器&本地Linxu服务器
        String saveDir = Properties.ImgSaveDir_Linux + sdf.format(new Date());

        //TODO:本地Windows服务器
//        String saveDir = Properties.ImgSaveDir_Windows + sdf.format(today);

        /*获取上传图片文件，存储到本地*/
        UploadFile titleImage = getFile("titleImage", saveDir);

        LOGGER.info("上传图片信息： " + titleImage.getSaveDirectory() + titleImage.getFileName());
        if (titleImage == null) {
            LOGGER.error("上传图片未获取到...");
        }

        int pageId = getParaToInt("pageId");
        /*压缩图片*/
        String inputDir = saveDir;
        String outputDir = saveDir;
        String inputFileName = titleImage.getFileName();
        /*************************************/
        String dateUnixStr = String.valueOf(new Date().getTime()); //unix时间的字符串形式：1. imageId; 2. 文件名前缀;
        String dateStr = sdf.format(today); // 日期的格式化字符串表示

        /*************************************/

        //图片重命名
        String outputFileName = dateUnixStr + ".jpg";
        File uploadImg = new File(saveDir + inputFileName);
        uploadImg.renameTo(new File(outputDir + outputFileName));


        //将标题图片上传到OSS
        String titleImgUrl = new String();
        try {
            titleImgUrl = ReplaceImgURL.replaceTitleUrl(outputDir + outputFileName);
        } catch (IOException e) {
            LOGGER.error("将标题图片上传到OSS出错", e);
        }

        // 存储压缩后的图片地址到数据库
        try {
            new PageTitleImage().set("imageId", dateUnixStr).set("imageSource", titleImgUrl).save();
        } catch (Exception exception) {
            LOGGER.error("存储压缩后的原图到数据库出错", exception);
        }

        /*删除原文件*/
        File image = new File(inputDir + inputFileName);
        if (image.exists()) {
            image.delete();
        }

        /*删除压缩后的存于本地的图片*/
        File image2 = new File(outputDir + outputFileName);
        if (image2.exists()) {
            image2.delete();
        }

        //TODO:本地Windows服务器
        //String imageSrc = Properties.ImgSrc_Windows + sdf.format(new Date()) + outputFileName;

        //TODO:本地linux服务器
        //String imageSrc = Properties.ImgSrc_LocalLinux + sdf.format(new Date()) + outputFileName;

        //TODO:云端服务器
//        String imageSrc = Properties.ImgSrc_CloudServer + sdf.format(new Date()) + outputFileName;


        /*向裁剪页面发送图片信息*/
        setAttr("src", titleImgUrl);
        /*图片物理地址发送到客户端*/
        setAttr("localPicPath", saveDir + outputFileName);
        setAttr("imageId", dateUnixStr); // 发送图片imageId到客户端
        setAttr("pageId", pageId);
        renderJsp("/reUploadAndCutImage.jsp");
    }

    /**
     * 剪切图片并保存
     * 调用接口：http://ipaderess/editorJfinalProject/edit/cutImage
     */
    public void cutImage() {

        int x = getParaToInt("x");
        int y = getParaToInt("y");
        int w = getParaToInt("w");
        int h = getParaToInt("h");

        int x1 = getParaToInt("x1");
        int y1 = getParaToInt("y1");
        int w1 = getParaToInt("w1");
        int h1 = getParaToInt("h1");

        String src = getPara("src");
        String imageId = getPara("imageId");
        int imageType = getParaToInt("imgType");

        /**
         * 剪裁后的图片存储文件为 desImageFile(File)
         */
        //TODO:云服务器&本地Linxu服务器
//        String saveDir = Properties.ImgSaveDir_Linux + sdf.format(new Date());

        //TODO:本地Windows服务器
        //String saveDir = Properties.ImgSaveDir_Windows + sdf.format(today);

        /**
         * 对原图进行裁剪，裁剪后的图片存储到 desImageFile
         */

        /**
         * 把裁剪后的图片的地址存储到数据库
         */
        String newsrc = src + "@" + x + "-" + y + "-" + w + "-" + h + "a";
        String newsrc2 = src + "@" + x1 + "-" + y1 + "-" + w1 + "-" + h1 + "a";
        try {
            PageTitleImage.pageTitleImageDao.findById(imageId).set("imageSrc", newsrc).set("pageImageSrc",newsrc2).update();
        } catch (Exception exception) {
            LOGGER.error("标题图片上传到数据库失败...", exception);
        }

        /**
         * 发送默认日期参数
         */
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Date dt = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(dt);
        calendar.add(calendar.DATE, 1);//把日期往后增加 1 天.整数往后推,负数往前移动
        dt = calendar.getTime(); //这个时间就是日期往后推 1 天的结果
        String dateString = simpleDateFormat.format(dt);

        setAttr("dateStr", dateString); //默认日期参数
        setAttr("imageId", imageId); //图片ID
        setAttr("imgType",imageType);

        renderJsp("/edit.jsp");

    }

    /*对更换的图片裁剪*/
    public void reCutImage() {

        int pageId = getParaToInt("pageId");
        int x = getParaToInt("x");
        int y = getParaToInt("y");
        int w = getParaToInt("w");
        int h = getParaToInt("h");

        int x1 = getParaToInt("x1");
        int y1 = getParaToInt("y1");
        int w1 = getParaToInt("w1");
        int h1 = getParaToInt("h1");


        String imageId = getPara("imageId");
        String src = getPara("src");
        int imageType = getParaToInt("imgType");

        /**
         * 把裁剪后的图片的地址存储到数据库
         */
        String newsrc = src + "@" + x + "-" + y + "-" + w + "-" + h + "a";
        String newsrc2 = src + "@" + x1 + "-" + y1 + "-" + w1 + "-" + h1 + "a";

        try {
            PageTitleImage.pageTitleImageDao.findById(imageId).set("imageSrc", newsrc).set("pageImageSrc",newsrc2).update();
            PageEdit.pageEditDao.findById(pageId).set("titleImage",imageId).set("infoImgType",imageType).update();
        } catch (Exception exception) {
            LOGGER.error("标题图片上传到数据库失败...", exception);
        }

        PageEdit.pageEditDao.updatePic(pageId, imageId);
        renderJsp("/page/editorPage.jsp");
    }

    /**
     * ajax对标题查重
     */
    public void checkTitle() {
        String title = getPara("pageTitle");
        int flag = PageEdit.pageEditDao.getPageByTitle(title);

        if (flag == 1) {
            setAttr("flag", flag);
            setAttr("information", "这是一篇新文章");
            renderJson();
        } else {
            setAttr("flag", flag);
            setAttr("information", "文章已存在！");
            renderJson();
        }
    }

    /**
     * 提交编辑内容
     * 调用接口：http://ipaderess/editorJfinalProject/edit/submitEdit
     */
    public void submitEdit() throws IOException {
        Date date = getParaToDate("date"); //文章推送时间的标识
        int editThirdId = getParaToInt("editThirdId"); //三级分类-编辑部门ID
        String title = getPara("title"); //文章标题
        String source = getPara("source"); //文章来源
        String imageId = getPara("imageId"); //图片ID
        int imageType = getParaToInt("imgType");
        String content = getPara("content"); //文章内容
        String sourceAddress = getPara("sourceAddress"); //文章源网址

        // 从session域中取出editorId
        String editorId = (String) getSession().getAttribute("editorId");

        if (editorId == null) {
            editorId = "100"; // 针对目前情况,防止因为取不到session里面的editorId而需要editor重新上传
        }

        // 存储编辑好的文章之前，对上传信息做一些处理
        PageEdit pageEdit = PageEdit.pageEditDao.processBeforeStore(editorId, date, editThirdId, title, source, imageId, imageType, content, sourceAddress);
        //判断取得的结果是否为空
        if (pageEdit == null) {
            renderHtml("文章已经存在！或者你的分类选择错误！");
        } else {
            /*把数据存储到数据库,storePageInfo(PageInfo)*/
            PageEdit.pageEditDao.storePageInfo(pageEdit);

            renderJsp("/newUploadAndCutImage.jsp");
        }

    }

    /**
     * 修改文章secondTitle,作为推荐页面的标题
     */
    public void updateSecTitle() {
        int pageId = getParaToInt("pageId");
        String secondTitle = getPara("secondTitle");

        PageEdit.pageEditDao.updateSecTitle(pageId, secondTitle);

        setAttr("flag", 1);
        setAttr("title", secondTitle);
        renderJson();
    }

    /**
     * 修改标题，日期，以及分类
     */
    public void changeTopInfo() {
        int pageId = getParaToInt("pageId");
        String newTitle = getPara("newTitle");
        String newSource = getPara("sourceAddress");
        String newFrom = getPara("pageFrom");
        Date newDate = getParaToDate("newDateFlag");

//        String dateString = newDate(newDateFlag);

        int newEditThirdId = getParaToInt("newEditThirdId");
        int thirdID = TypeInfo.typeInfoDao.getThirdIdByEditor(newEditThirdId);
        PageEdit.pageEditDao.findById(pageId).set("firstTitle", newTitle).set("pageDate", newDate).set("pageFrom", newFrom).set("sourceAddress", newSource).set("typeId", thirdID).update();

        setAttr("flag", 1);
        renderJson();
    }

    /**
     * 将flag转换为日期
     *
     * @param dateFlag
     * @return
     */
    public String newDate(int dateFlag) {
        Date dt = new Date();
        Calendar calendar = new GregorianCalendar();
        switch (dateFlag) {
            case 0:
                calendar.setTime(dt);
                dt = calendar.getTime();//将数字转化为日期，为今天
                break;
            case 1:
                calendar.setTime(dt);
                calendar.add(calendar.DATE, 1);//把日期往后增加 1 天.整数往后推,负数往前移动
                dt = calendar.getTime(); //这个时间就是日期往后推 1 天的结果
                break;
            case 2:
                calendar.setTime(dt);
                calendar.add(calendar.DATE, 2);
                dt = calendar.getTime();
                break;
            case 3:
                calendar.setTime(dt);
                calendar.add(calendar.DATE, 3);
                dt = calendar.getTime();
                break;
        }

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(dt);
        return dateString;
    }

    /**
     * 令文章提前进入APP，即直接进入page_info表
     */
    public void gotoApp() {
        int pageId = getParaToInt("pageId");
        if(PageInfo.pageInfoDao.isInApp(pageId)){
            setAttr("message","已经在APP中!");
            renderJson();
            return;
        }
        if (PageInfo.pageInfoDao.addOneInfo(pageId)){
            setAttr("message","上传成功！");
        }else {
            setAttr("message","上传失败！");
        }
        renderJson();
    }

    /**
     * 跳转到修改文章正文
     */
    public void changePage() {
        int pageId = getParaToInt("pageId");
        List<Record> recordList = Db.find("SELECT pageContent FROM page_edit WHERE id=?", pageId);
        String pageContent = recordList.get(0).get("pageContent");
        //pageContent = pageContent.replaceAll("\n", "");
        pageContent = HtmlStringHandler.restoreHtml(pageContent);

        setAttr("pageId", pageId);
        setAttr("oldPageContent", pageContent);
        renderJsp("/reEdit.jsp");
    }

    /**
     * 更新文章
     */
    public void updatePage() throws IOException {
        int pageId = getParaToInt("pageId");
        String content = getPara("content");
        String editorId = (String) getSession().getAttribute("editorId");
        PageEdit.pageEditDao.updatePage(pageId, content);
        if(PageInfo.pageInfoDao.isInApp(pageId)){
            PageInfo.pageInfoDao.updateAppPage(pageId,content);
            LOGGER.error("紧急同步了一篇app文章，文章page_edit的Id为：" + pageId);
        }
        redirect(Properties.Server_IP + "/editorJfinalProject/page/editorPage/" + editorId + "-1");
    }

    /**
     * 申请更新图片
     */
    public void changePic() {
        int pageId = getParaToInt("pageId");
        setAttr("pageId", pageId);
//        System.out.println(pageId);
        renderJsp("/reUploadAndCutImage.jsp");
    }

}
